package im.yisme.server.servlet;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUpload;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.RequestContext;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.servlet.ServletRequestContext;

import com.alibaba.fastjson.JSONObject;

public class UploadFileServlet extends HttpServlet{

	/**
	 * 
	 */
	private static final long serialVersionUID = 7706421097771100980L;
	private String bath;
	private String remoteId = null;
	private FileItem lyricsFile = null;
	
	public void doGet(HttpServletRequest request, HttpServletResponse response){
		doPost(request, response);
	}
	
	@SuppressWarnings("deprecation")
	public void doPost(HttpServletRequest request, HttpServletResponse response){
		CharacterEncoding.setCharacterEncoding(request, response);
		
		bath = request.getRealPath("/");
		JSONObject jsonObject = new JSONObject();
		
		RequestContext context = new ServletRequestContext(request);
		parseFile(context, request);
		
		if (remoteId == null || remoteId.length() == 0){
			jsonObject.put("flag", "false");
		} 
		else if (lyricsFile != null){
			try {
				saveFile();
				jsonObject.put("flag", "true");
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				jsonObject.put("flag", "false");
			}
		}
		
		try {
			response.getWriter().print(jsonObject.toJSONString());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	@SuppressWarnings("unchecked")
	private void parseFile(RequestContext context, HttpServletRequest request){
		if (FileUpload.isMultipartContent(context)){
			String path = bath + "temp";
			File file = new File(path);
			if (!file.exists() || !file.isDirectory())
				file.mkdirs();
			
			DiskFileItemFactory factory = new DiskFileItemFactory();
			factory.setRepository(file);
			ServletFileUpload upload = new ServletFileUpload(factory);
			upload.setSizeMax(1024 * 10);
			List<Object> items = new ArrayList<Object>();
			
			try {
				items = upload.parseRequest(request);
			} catch (FileUploadException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			Iterator<Object> it = items.iterator();
			while(it.hasNext()){
				FileItem fileItem = (FileItem)it.next();
				
				if (fileItem.isFormField()){
					String fieldName = fileItem.getFieldName();
					if (!fieldName.equals("remoteId")) continue;
					remoteId = new String(fileItem.getString());
				}
				else{
					String fieldName = fileItem.getFieldName();
					if (!fieldName.equals("file")) continue;
					
					if (fileItem.getName() != null && fileItem.getSize() != 0){
						String fileName = fileItem.getName();
						int index = fileName.lastIndexOf(".");
						if (!fileName.substring(index).equals(".ylrc")) continue;
						lyricsFile = fileItem;
					}
				}
			}
		}
	}
	
	private void saveFile() throws Exception{
		File dirFile = new File(bath + "lyrics");
		if (!dirFile.exists() || !dirFile.isDirectory())
			dirFile.mkdirs();	
		
		File newFile = new File(bath + "lyrics/" + remoteId + ".ylrc");
		lyricsFile.write(newFile);
	}
}
